package com.lingnan.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingnan.entity.NotificationDTO;
import com.lingnan.entity.NotificationEntity;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

// NotificationMapper.java
@Mapper
public interface NotificationMapper extends BaseMapper<NotificationEntity> {

    /**
     * 批量插入通知
     */
    @Insert({
            "<script>",
            "INSERT INTO notification (sender_id, receiver_id, receiver_type, title, content, type, status, created_at) VALUES ",
            "<foreach collection='notifications' item='item' index='index' separator=','>",
            "(#{item.senderId}, #{item.receiverId}, #{item.receiverType}, #{item.title}, #{item.content}, #{item.type}, #{item.status}, #{item.createdAt})",
            "</foreach>",
            "</script>"
    })
    void batchInsert(@Param("notifications") List<NotificationEntity> notifications);
    
    @Select("SELECT n.*, ua.nick_name as sender_name FROM notification n " +
            "LEFT JOIN user_account ua ON n.sender_id = ua.id " +
            "WHERE n.receiver_id = #{userId} OR " +
            "(n.receiver_type = 2 AND NOT EXISTS (" +
            "  SELECT 1 FROM notification_receiver nr " +
            "  WHERE nr.notification_id = n.id AND nr.receiver_id = #{userId}" +
            ")) " +
            "ORDER BY n.created_at DESC")
    List<NotificationDTO> selectUserNotifications(@Param("userId") Long userId);
    
    @Select("SELECT COUNT(*) FROM notification n " +
            "WHERE (n.receiver_id = #{userId} AND n.status = 0) OR " +
            "(n.receiver_type = 2 AND n.status = 0 AND NOT EXISTS (" +
            "  SELECT 1 FROM notification_receiver nr " +
            "  WHERE nr.notification_id = n.id AND nr.receiver_id = #{userId} AND nr.status = 1" +
            "))")
    int countUnreadNotifications(@Param("userId") Long userId);
}